package com.kaiwukj.android.ufamily.mvp.ui.page.order.refund;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.StringUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerOrderComponent;
import com.kaiwukj.android.ufamily.di.module.OrderModule;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.OrderRefundParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.HouseKeeperResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.OrderDetailResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.OrderResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.ImageAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.order.OrderContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.order.OrderPresenter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.order.OrderResultActivity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.OrderRefundUrl)
public class OrderRefundActivity extends BaseMvpActivity<OrderPresenter> implements OrderContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_service_type)
    TextView tvServiceType;
    @BindView(R.id.tv_service_price)
    TextView tvServicePrice;
    @BindView(R.id.tv_service_count)
    TextView tvServiceCount;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.container_amount)
    ViewGroup containerAmount;
    @BindView(R.id.tv_refund_amount)
    TextView tvRefundAmount;
    @BindView(R.id.tv_discount)
    TextView tvDiscount;
    @BindView(R.id.container_reason)
    ViewGroup containerReason;
    @BindView(R.id.tv_reason)
    TextView tvReason;
    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.rv_image)
    RecyclerView rvImage;

    private ImageAdapter mUploadAdapter;


    private String reason;

    @Autowired
    int refundType;//退款类型（0:服务未发生申请退款 1:投诉退款 ）
    @Autowired
    OrderDetailResult order;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick(R.id.container_reason)
    void onReasonClick() {
        new QMUIBottomSheet.BottomListSheetBuilder(this)
                .addItem("服务质量问题")
                .addItem("服务态度问题")
                .addItem("服务不对称")
                .addItem("未按约定时间上门")
                .addItem("不想要了")
                .addItem("其他")
                .setGravityCenter(true)
                .setOnSheetItemClickListener((dialog1, itemView, position12, tag) -> {
                    reason = tag;
                    tvReason.setText(tag);
                    dialog1.dismiss();
                }).build().show();
    }

    @OnClick(R.id.btn_submit)
    void onSubmit() {
        OrderRefundParams params = new OrderRefundParams();
        params.setOrderId(order.getId());
        params.setOrderNum(order.getOrderNum());
        params.setRefundType(refundType);
        List<String> imgList = mUploadAdapter.getData();

        if (StringUtils.isEmpty(reason)) {
            showMessage("请选择原因");
            return;
        }
        params.setReason(reason);
        String desc = etDesc.getText().toString().trim();
        if (!StringUtils.isEmpty(desc)) {
            params.setDescription(desc);
        }
        mPresenter.submitRefund(params, imgList);
        //mPresenter.refundOrder(params);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_order_refund;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerOrderComponent.builder()
                .appComponent(appComponent)
                .orderModule(new OrderModule(this))
                .build().inject(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (refundType == 0) {
            tvTitle.setText("申请退款");
        } else {
            tvTitle.setText("投诉退款");
        }

        if (refundType == 1) {
            containerAmount.setVisibility(View.GONE);
            tvPhone.setText("联系客服");
        } else {
            tvRefundAmount.setText(String.format("¥%s", order.getActualPriceStr()));
        }

        if (order == null) {
            showMessage("订单信息获取失败");
        } else {
            tvServiceType.setText(order.getServiceParameterName());
            tvServicePrice.setText(order.getUnitPriceStr());
            tvServiceCount.setText(String.valueOf(order.getNum()));
            tvPhone.setOnClickListener(v -> mPresenter.getKeeper());
        }

        rvImage.setLayoutManager(new GridLayoutManager(this, 4));
        mUploadAdapter = new ImageAdapter();
        mUploadAdapter.setMaxCount(3);
        rvImage.setAdapter(mUploadAdapter);
        mUploadAdapter.setOnItemClickListener(new ImageAdapter.onItemClickListener() {
            @Override
            public void onAddClick() {
                pickImage();
            }

            @Override
            public void onDelClick(int position) {
                mUploadAdapter.remove(position);
            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
                PopupWindowUtil.createImageDialog(OrderRefundActivity.this,
                        imgUrls.get(position)).showCenter(R.layout.activity_order_refund);
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    private void pickImage() {
        PictureSelector.create(OrderRefundActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .isCompress(true)
                .maxSelectNum(3 - mUploadAdapter.getData().size())
                .imageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.MyImagePickerStyle)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        List<String> path = new ArrayList<>();
                        for (LocalMedia media : result) {
                            path.add(media.getCompressPath());
                        }
                        mUploadAdapter.addData(path);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onFetchOrder(List<OrderResult> results) {

    }

    @Override
    public void onGetOrder(OrderDetailResult result) {

    }

    @Override
    public void onOrderPayResult(Map<String, Object> result) {

    }

    @Override
    public void onGetHouseKeeper(HouseKeeperResult result) {
        String phone = result.getPhone();
        showMessageOKCancel(this, String.format("拨打:%s", phone),
                v1 -> startActivity(IntentUtils.getDialIntent(phone)));
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == OrderPresenter.REFUND) {
            showMessage("提交成功");
            ARouter.getInstance().build(ARouterUrlKt.OrderResultUrl)
                    .withInt("type", OrderResultActivity.ORDER_REFUND)
                    .withInt("orderId", order.getId())
                    .navigation();
        }
    }
}
